package com.gues.controller;

import com.gues.eneity.User;
import com.gues.result.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
public class LoginController {


    @RequestMapping("/")
    public String init() {
        return "login";
    }

    @RequestMapping("/login")
    public String login() { return "login"; }

    @PostMapping("/toLogin")
    public @ResponseBody
    Result toLogin(@RequestBody User user) {
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(user.getUsername(), user.getPassword()));
            return new Result(200);
        } catch (AuthorizationException ignored) {
            return new Result(403, "账号或密码错误");
        }
    }

    @RequestMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login";
    }

    @RequestMapping("/index")
    public String index() {
        return "index";
    }
}
